<script setup lang="ts">
import { onMounted, ref } from 'vue'
import useKonva from '@/composables/useKonva'
import Konva from 'konva'

interface Point {
  x: number
  y: number
}

// konva容器
const container = ref<HTMLDivElement>()
const { layer, imageScale, initStage, initImage } = useKonva()

// 绘制路径
function drawPath(list: Point[]): void {
  const pointGroup = layer.value.children[1]
  pointGroup.removeChildren()
  if (list.length > 1) {
    const points: number[] = []
    list.forEach((point) => {
      points.push(point.x)
      points.push(point.y)
    })
    pointGroup.add(new Konva.Line({ stroke: '#f90', strokeWidth: 1, points }))
  }
  list.forEach((item, index) => {
    const point = new Konva.Group({ x: item.x, y: item.y })
    const text = String(index + 1)
    const circle = new Konva.Circle({ radius: 3, fill: '#e33' })
    const marker = new Konva.Text({ text, fontSize: 3, fill: '#fff' })
    marker.offset({ x: marker.width() / 2, y: 1.2 })
    point.add(circle).add(marker)
    pointGroup.add(point)
  })
}

// 预览路径
function previewPath(list: Point[]): void {
  list.forEach((element) => {
    element.x *= imageScale.value
    element.y *= imageScale.value
  })
  drawPath(list)
}

// 实时路径
function realTimePath(list: Point[]): void {
  if (list.length > 1) {
    const points: number[] = []
    list.forEach((point) => {
      points.push((point.x *= imageScale.value))
      points.push((point.y *= imageScale.value))
    })
    layer.value.children[1].add(
      new Konva.Line({
        stroke: '#20fea5',
        strokeWidth: 1,
        opacity: 0.6,
        lineCap: 'round',
        lineJoin: 'round',
        points
      })
    )
  }
}

onMounted(() => {
  if (container.value) {
    initStage('stage', container.value.offsetWidth, container.value.offsetHeight)
  }
})

defineExpose({ previewPath, initImage, realTimePath })
</script>

<template>
  <div ref="container" class="h-full relative">
    <div id="stage" class="flex justify-center bg-[#0D1A29]"></div>
  </div>
</template>
